<template>
  <n-layout class="text-black">
    <n-layout-header class="header flex flex-ai-center bg-gray">
      <n-button class="fs-lg" text @click="$router.push('/')">
        <template #icon>
          <n-icon :size="20"><BookOutline /></n-icon>
        </template>
        首页
      </n-button>
      <n-button class="ml-4 fs-lg" text @click="$router.push('/books')">
        所有图书
      </n-button>
      <div class="flex-1"></div>
      <n-badge class="mr-4" type="warning" :value="cars.length" processing>
        <n-button @click="drawerStatus = !drawerStatus" class="fs-lg" text
          >购物车</n-button
        >
      </n-badge>
      <div>
        <n-dropdown
          v-if="user.username"
          @select="handleSelect"
          trigger="hover"
          :options="options"
        >
          <n-button class="fs-lg" :keyboard="false" text>{{
            user.username
          }}</n-button>
        </n-dropdown>
        <n-button class="fs-lg" v-else @click="$router.push(`/login`)" text
          >登录</n-button
        >
      </div>
    </n-layout-header>
    <n-layout-content>
      <div class="search bg-gray flex flex-ai-center flex-jc-center">
        <n-input
          @keydown.enter="handleSearch"
          size="large"
          style="width: 75%"
          v-model:value="keywords"
          placeholder="搜索"
          round
        >
          <template #suffix>
            <n-icon><Search /></n-icon>
          </template>
        </n-input>
      </div>
      <div class="content">
        <router-view></router-view>
      </div>
    </n-layout-content>
    <n-layout-footer class="footer text-center bg-gray">
      <span>Copyright © 2020 - 2021 zoneaurora. All Rights Reserved.</span>
    </n-layout-footer>
  </n-layout>
  <n-drawer v-model:show="drawerStatus" :width="370">
    <n-drawer-content title="购物车">
      <div class="flex flex-column h-100">
        <n-list class="flex-1" bordered v-if="cars.length > 0">
          <n-list-item v-for="item of cars" :key="item._id">
            <car-item :item="item"></car-item>
          </n-list-item>
        </n-list>
        <div class="flex-1 flex flex-ai-center flex-jc-center" v-else>
          <n-empty size="large" description="你什么也找不到"> </n-empty>
        </div>
        <div class="flex flex-ai-center flex-jc-between">
          <div class="fs-xl">
            总计: <span style="color: red">{{ calcPrice }}</span>
          </div>
          <n-button @click="finishOrder" type="error">结算</n-button>
        </div>
      </div>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts">
import { defineComponent, ref, provide, watch } from "vue";
import { BookOutline, Search } from "@vicons/ionicons5";
import {
  NLayout,
  NLayoutHeader,
  NLayoutContent,
  NLayoutFooter,
  NButton,
  NBadge,
  NDrawer,
  NDrawerContent,
  NInput,
  NIcon,
  NDropdown,
  NList,
  NListItem,
  NEmpty,
  useMessage,
} from "naive-ui";

import CarItem from "../components/CarItem.vue";
import { useRouter } from "vue-router";
import { useUser } from "../hooks/UseUsers";
import { useCars } from "../hooks/UseCars";
import { useOrder } from "../hooks/UseOrders";

export default defineComponent({
  name: "Index",
  components: {
    NLayout,
    NLayoutHeader,
    NLayoutContent,
    NLayoutFooter,
    NButton,
    NBadge,
    NDrawer,
    NDrawerContent,
    NInput,
    NIcon,
    BookOutline,
    Search,
    NDropdown,
    NList,
    NListItem,
    NEmpty,
    CarItem,
    useMessage,
  },
  setup() {
    const message = useMessage();
    const router = useRouter();
    const drawerStatus = ref(false);
    const { user, getUser } = useUser();
    const { cars, calcPrice, getCars } = useCars();
    const { order, getOrder, updateOrderStatus } = useOrder();

    getUser();
    getOrder();
    watch(order, () => {
      localStorage?.token && getCars(order.value._id);
    });

    async function flash() {
      await getOrder();
      await getCars(order.value._id);
    }

    async function finishOrder() {
      try {
        await updateOrderStatus(1);
        message.success("提交订单成功");
      } catch (e) {
        message.error("提交订单失败");
      }
      flash();
    }

    provide("order", order);
    provide("flash", flash);

    const options = ref([
      {
        label: "用户中心",
        key: "/user/info",
      },
      {
        label: "退出登录",
        key: "",
      },
    ]);

    function handleSelect(key: string) {
      if (!key) {
        localStorage.clear();
        router.go(0);
      } else {
        router.push(key);
      }
    }

    const keywords = ref("");

    function handleSearch() {
      router.push(`/books/${keywords.value}`);
    }

    return {
      drawerStatus,
      handleSelect,
      user,
      getUser,
      options,
      cars,
      getCars,
      calcPrice,
      keywords,
      handleSearch,
      order,
      finishOrder,
    };
  },
});
</script>

<style lang="scss" scoped>
.header {
  height: 4rem;
  padding: 0 2rem;
}

.search {
  height: 12rem;
}

.content {
  padding: 5rem 2rem;
  margin: 0 auto;
  width: 1000px;
}

.footer {
  padding: 6rem 0;
}

@media screen and (max-width: 1000px) and (min-width: 600px) {
  .content {
    width: 600px;
  }
}
@media screen and (max-width: 600px) {
  .content {
    width: 100%;
    margin: 0;
  }
}
</style>
